﻿using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Services;
using SelfMadeMillionaire.Web.Infrastructure.Controllers;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.Account;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.PayPal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Security;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{	
	public class AccountController : BaseController
	{
		//[Authorize]
		//public ActionResult Index()
		//{
		//	return RedirectToAction("Index", "Publications");
		//}

		readonly ISubscriberService _subscriberService;
        readonly IEmailService _emailService;
        IMailingListService _mailingListService;

        public AccountController(ISubscriberService subscriberService, IEmailService emailService, IMailingListService mailingListService)
		{
			_subscriberService = subscriberService;
            _emailService = emailService;
            _mailingListService = mailingListService;
		}

		[HttpGet]
		public ActionResult Login(string returnUrl)
		{
            if (Request.QueryString["webinar"] != null)
            {
                Session["Subscribe4webinar"] = true;
            }

            LoginViewModel model = new LoginViewModel();
            model.ReturnUrl = returnUrl;

			return View(model);
		}

		[HttpPost]
		public ActionResult Login(LoginViewModel model)
		{
			var subscriber = _subscriberService.Get(model.Email);

            if (subscriber != null && subscriber.PasswordHash == PasswordUtility.GetPasswordHash(model.Password))
            {
                if (subscriber.Status != (byte)StatusType.Active)
                {
                    // SMM-157
                    // акаут зарегистрирован, но не активирован
                    // надо вывести предупреждающий диалог
                    // и ссылку на повторную отправку линка для активации
                    model.Token = subscriber.Token;
                }
                else
                {
                    Authenticate(model.Email, subscriber.FirstName, subscriber.LastName, subscriber.EndDate.HasValue ? subscriber.EndDate.Value : DateTime.Now.AddDays(7), ((int)GetUserRole(subscriber)).ToString(), model.RememberMe);
                    if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        if (Session["Subscribe4webinar"] != null)
                        {
                            return RedirectToAction("WebinarConfirmation", "Home");
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                        Response.Redirect(model.ReturnUrl, endResponse: true);                        
                }
            }
            else
            {
                var adminLogin = WebConfigurationManager.AppSettings["AdminLogin"];
                var adminPassword = WebConfigurationManager.AppSettings["AdminPassword"];

                if (model.Email.ToLower() == adminLogin.ToLower() && model.Password == adminPassword)
                {
                    Authenticate(model.Email, null, null, DateTime.Now.AddDays(1), ((int)UserRole.Admin).ToString(), false);
                    return RedirectToAction("Index", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "User with this login and password is not found.");
                }
            }
			return View(model);
		}

        [HttpGet]
        public ActionResult PasswordRecovery()
        {
            return View();
        }

        [HttpGet]
        public ActionResult PasswordReset()
        {
            int i = 0;
            i++;
            foreach(var s in _mailingListService.GetSubscribers(null, null, null, null).ToList().Where(x => x.PasswordHash == "pass"))
            {
                var ss = _subscriberService.Get(s.ID);
                ss.PasswordHash = PasswordUtility.GetPasswordHash(ss.Email.ToLower());

                _subscriberService.Update(ss);
            }

            return null;
        }

        [HttpPost]
        public ActionResult PasswordRecovery(PasswordRecoveryModel model)
        {
            foreach (var modelValue in ModelState.Values)
            {
                modelValue.Errors.Clear();
            }

            model.PasswordRecoveryIsSuccess = null;
            if (string.IsNullOrEmpty(model.PasswordRecoveryEmail))
                model.PasswordRecoveryMessage = "The Email field is required.";
            else
            {
                model.PasswordRecoveryIsSuccess = true;
                model.PasswordRecoveryMessage = "We have sent you instructions on how to get a new password. Please check your email account (it might be in your spam folder)";

                var subscriber = _subscriberService.Get(model.PasswordRecoveryEmail);
                if ((subscriber != null) && (subscriber.Status == (byte)StatusType.Active))
                {
                    _subscriberService.CreatePasswordRecovery(subscriber);

                    try
                    {
                        if (_emailService.SendPasswordRecoveryEmail(subscriber))
                        {
                            ModelState.Remove("PasswordRecoveryEmail");
                            model.PasswordRecoveryEmail = "";
                        }
                        else
                        {
                            model.PasswordRecoveryMessage = "Unexpecter Error: cannot send out the password recovery email.";
                            model.PasswordRecoveryIsSuccess = false;
                        }
                    }
                    catch (Exception)
                    {
                        model.PasswordRecoveryMessage = "Unexpecter Error: cannot send out the password recovery email.";
                        model.PasswordRecoveryIsSuccess = false;
                    }
                }
            }

            return View("PasswordRecovery", model);
        }

        [HttpGet]
        public ActionResult ResetPassword(string key)
        {
            Guid keyGuid;
            if (Guid.TryParse(key, out keyGuid))
            {

                Subscriber subscriber = _subscriberService.GetByPasswordRecoveryKey(keyGuid);
                ResetPasswordViewModel model = new ResetPasswordViewModel();

                if (subscriber != null)
                    model.Key = keyGuid;

                return View("ResetPassword", model);

            }

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                Subscriber subscriber = _subscriberService.GetByPasswordRecoveryKey(model.Key);
                if (subscriber != null)
                {
                    subscriber.PasswordHash = PasswordUtility.GetPasswordHash(model.Password);
                    subscriber.PasswordRecoveryKey = null;
                    _subscriberService.Update(subscriber);


                    Authenticate(subscriber.Email, subscriber.FirstName, subscriber.LastName, subscriber.EndDate.HasValue ? subscriber.EndDate.Value : DateTime.Now.AddDays(7), ((int)GetUserRole(subscriber)).ToString(), false);
                    return RedirectToAction("Index", "Home");
                }
            }
            
            return View("ResetPassword", model);
        }

		[HttpGet]
		public ActionResult LogOut()
		{
			FormsAuthentication.SignOut();
			return RedirectToAction("Login");
		}

        public ActionResult SendActivationEmail(Guid token)
        {
            var subscriber = _subscriberService.Get(token);

            if (subscriber != null)
            {
                _emailService.SendActivationEmail(subscriber);
            }

            return RedirectToAction("Login", "Account");
        }

		[HttpGet]
		public ActionResult Activate(string token)
		{
            Guid tokenGuid;
            if (Guid.TryParse(token, out tokenGuid))
            {
                var subscriber = _subscriberService.Get(tokenGuid);

                if (subscriber != null)
                {
                    Authenticate(subscriber.Email, subscriber.FirstName, subscriber.LastName, subscriber.EndDate.HasValue ? subscriber.EndDate.Value : DateTime.Now.AddDays(7), ((int)GetUserRole(subscriber)).ToString(), true);

                    subscriber.Token = null;
                    _subscriberService.Activate(subscriber);

                    return RedirectToAction("Activated", "Profile");
                }
            }

			return RedirectToAction("Index", "Home");
		}
	}
}
